require 'open-uri'

class FoneFinder
	def initialize(number)
		if(validPhoneNumber(number) == nil) 
			puts "Error invalid phone number"
			@invalid = true
			return
		end
		@invalid = false
		@number = number
		@area = @number[0,3]
		@prefix = @number[3,3]
		@thoublock = @number[6,4]
		@url = makeURL(number)
		scrape #assigns values to the rest of the properties
	end	
	def invalid
		@invalid
	end
	def area
		@area
	end
	def prefix
		@prefix
	end
	def thoublock
		@thoublock
	end
	def number
		@number
	end
	def city
		@city
	end
	def state
		@state
	end
	def carrier
		@carrier
	end
	def url
		@url
	end

	# canoncalize a phone number
	private
	def validPhoneNumber (number)
		if number.is_a? String
			number = number.gsub!(/ *-*\(*\)*/, "")	
			if number.size == 10
				if number.match(/([0-9]){10}/)
					return number;
				end
			end
		end
		return nil;
	end	

	# create a URL
	private
	def makeURL(number)
		url = "http://www.fonefinder.net/findome.php?npa=" + @area + "&nxx=" + @prefix + "&thoublock=" + @thoublock + "&usaquerytype=Search+by+Number&cityname="
		return url
	end

	private

	# filthy scraping
	private
	def scrape
		html = (open(@url).read)
		start = "<TABLE border=3 cellspacing=2"
		start = html.index(start)
		if (start == nil)
			puts "Error invalid query"
			@invalid = true
			return
		end
		@invalid = false
		startAreaIndex = html.index("<A HREF='findareacode")
		html = html[startAreaIndex, html.size - startAreaIndex]
		start = "cityname="
		endChar = "&"
		start = html.index(start) + start.size
		html = html[start, html.size - start]
		endChar = html.index(endChar)
		@city = html[0,endChar]
		html = html[endChar, html.size - city.size]
		start = "&state="
		html = html[start.size, html.size - start.size]
		endChar = "\'"
		@state = html[0, html.index(endChar)]
		start = html.index(start)
		start = "</A><TD><A HREF='http://fonefinder.net"
		start = start.size + html.index(start)
		html = html [start, html.size - start]
		endChar = 1 + html.index(">")
		html = html[endChar, html.size - endChar]
		endChar = "<"
		@carrier = html[0, html.index(endChar)]
	end
end
